package main

import (
	"database/sql"
	"fmt"
	"os"

	"go-todo/handlers"

	_ "github.com/go-sql-driver/mysql"
	"github.com/labstack/echo"
	"github.com/labstack/echo/engine/standard"
)

func main() {

	db := initDB()
	migrate(db)

	e := echo.New()

	e.File("/", "public/index.html")
	e.Static("/public", "public")
	e.GET("/tasks", handlers.GetTasks(db))
	e.PUT("/tasks", handlers.PutTask(db))
	e.DELETE("/tasks/:id", handlers.DeleteTask(db))

	e.Run(standard.New(":8000"))

}

func initDB() *sql.DB {
	pw := os.Getenv("MYSQL_ROOT_PASSWORD")
	dbname := os.Getenv("MYSQL_DB_NAME")
	if pw == "" || dbname == "" {
		panic("Need MYSQL_ROOT_PASSWORD and MYSQL_DB_NAME")
	}
	host := os.Getenv("MYSQL_HOST")
	connection := fmt.Sprintf("root:%s@tcp(%s:3306)/%s?charset=utf8&parseTime=True&loc=Local",
		pw, host, dbname)
	db, err := sql.Open("mysql", connection)

	if err != nil {
		panic(err)
	}

	if db == nil {
		panic("db nil")
	}

	return db
}

func migrate(db *sql.DB) {
	sql := `
  CREATE TABLE IF NOT EXISTS tasks(
    id INTEGER NOT NULL AUTO_INCREMENT,
	PRIMARY KEY (id),
    name VARCHAR(100) NOT NULL
  );
  `

	_, err := db.Exec(sql)

	if err != nil {
		panic(err)
	}
}
